import { useState, useEffect } from 'react';
/** 监听网络变化hooks */
export const useNetwork = () => {
    /** 当前网络状态 */
    const [networkInfo, setNetworkInfo] = useState((() => {
        const { onLine, connection } = window.navigator;
        return {
            online: onLine,
            rtt: connection.rtt,
            downlink: connection.downlink,
            effectiveType: connection.effectiveType,
            saveData: connection.saveData
        };
    })());
    useEffect(() => {
        /** 设置当前网络状态 */
        const setCurrNetwork = () => {
            const { onLine, connection } = window.navigator;
            setNetworkInfo({
                online: onLine,
                rtt: connection.rtt,
                downlink: connection.downlink,
                effectiveType: connection.effectiveType,
                saveData: connection.saveData
            });
        };
        /** 开始监听 */
        window.addEventListener('online', setCurrNetwork, false);
        window.addEventListener('offline', setCurrNetwork, false);
        window.addEventListener('change', setCurrNetwork, false);
        /** 清除监听 */
        return () => {
            window.removeEventListener('online', setCurrNetwork, false);
            window.removeEventListener('offline', setCurrNetwork, false);
            window.removeEventListener('change', setCurrNetwork, false);
        };
    }, []);
    return networkInfo;
};
